/*
 * @Author: seanyan
 * @Date:   2021-09-13 16:21:33
 * @Last Modified by:   qinuoyun
 * @Last Modified time: 2021-09-24 14:40:16
 */
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

class LoginController extends BasicController {
    /**
     * 处理用户登陆
     * @return {[type]} [description]
     */
    async actionIndex() {
        let userInfo = await this.modules("Account").where({ "mobile": $_POST['mobile'] }).first();
        if (userInfo) {
            let password = this.getPassword($_POST['password']);
            if (userInfo["password"] == password) {
                //删除对应密码字段
                delete userInfo["password"];
                userInfo["token"] = this.getToken(userInfo);
                //返回用户数据
                return userInfo;
            } else {
                throw new Error('密码错误');
            }
        } else {
            throw new Error('用户不存在');
        }
    }

    /**
     * 注册用户
     * @return {[type]} [description]
     */
    async actionRegister() {
        let userInfo = await this.modules("Account").where({ "mobile": $_POST['mobile'] }).first();
        if (userInfo && userInfo.mobile) {
            throw new Error('注册的手机号已经存在');
        } else {
            $_POST['password'] = this.getPassword($_POST['password']);
            return this.modules("Account").insert($_POST);
        }
    }

    /**
     * 解析验证Token数据使用
     * @return {[type]} [description]
     */
    static findIdentityByAccessToken(token) {
        let self = new this();
        return new Promise((resolve, reject) => {
            let $data = jwt.verify(token.slice(7), __SECRET__);
            self.modules("Account").where({ "mobile": $data['name'] }).first().then(data => {
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        })
    }

    /**
     * 获取Token信息
     * @param  {[type]} USER [description]
     * @return {[type]}      [description]
     */
    getToken(USER) {
        return jwt.sign({
            name: USER.mobile,
            id: USER._id
        }, __SECRET__, { expiresIn: '12h' });
    }

    /**
     * 设置登陆密码
     * @param  {[type]} str [description]
     * @return {[type]}     [description]
     */
    getPassword(str) {
        let key = 'W4xOLXEvo*$8pk%aruoV!&t$5NAp0HHl';
        var obj = crypto.createHash('md5');
        obj.update(str + key);
        return obj.digest('hex');

    }
}
module.exports = LoginController;